const request = require('request');
const fs = require('fs');
const path = require('path');

const SINGLE = 1024 * 1024 * 100;

// const SOURCE = 'http://127.0.0.1:5000/IMG_5857.MOV';
const SOURCE = 'https://npm.taobao.org/mirrors/node/v14.3.0/node-v14.3.0-win-x64.zip';

console.time('down');
request({
    method: 'HEAD',
    uri: SOURCE
}, (err, res) => {
    if (err) return console.error(err);

    const type = SOURCE.split('.').slice(-1)[0];
    const file = path.join(__dirname, './download/test.' + type);

    try {
        fs.closeSync(fs.openSync(file, 'w'));
    } catch (err) {
        return console.error(err);
    }

    const size = Number(res.headers['content-length']);

    console.log(size);
    const length = Math.max(1, parseInt(size / SINGLE));

    for (let i = 0; i < length; i++) {
        let start = i * SINGLE;

        let end = (i !== (length - 1)) ? (i + 1) * SINGLE - 1 : size - 1;

        console.log(`start = ${start}, end = ${end}`);
        request({

            method: 'GET',
            uri: SOURCE,
            headers: {
                'range': `bytes=${start}-${end}`
            }

        }).on('response', (resp) => {
            const range = resp.headers['content-range'];
            // console.log(range);

            const match = /bytes ([0-9]*)-([0-9]*)/.exec(range);

            start = match[1];

            end = match[2];
        }).pipe(fs.createWriteStream(file, {start, end}));
    }
});

process.on('exit', (code) => {
    console.log(`退出码: ${code}`);
    console.timeEnd('down');
});
